/**
 * Licensed to Open-Ones Group under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Open-Ones Group licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a
 * copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package oog.product;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

public class ReqUtil {
    public static final Logger LOG = Logger.getLogger("ReqUtil");

    private static Map<String, Object> getMapData(HttpServletRequest req) {
        Map<String, Object> result = new HashMap<String, Object>();
        LOG.debug("getMapData.START:");
        Object bean = null;

        if (!ServletFileUpload.isMultipartContent(req)) { // Normal form data
            String fieldName;
            for (Enumeration<String> keyEnum = req.getParameterNames(); keyEnum.hasMoreElements();) {
                fieldName = keyEnum.nextElement();
                result.put(fieldName, req.getParameter(fieldName));
            }
            return result;
        } else { // Upload form data
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            ServletFileUpload portletFU = new ServletFileUpload(fileItemFactory);
            List items;
            try {
                items = portletFU.parseRequest(req);
                FileItem fit;
                String fieldName;
                String value;
                for (Iterator it = items.iterator(); it.hasNext();) {
                    fit = (FileItem) it.next();
                    fieldName = fit.getFieldName();

                    if (fit.isFormField()) { // Normal field
                        value = fit.getString();
                        result.put(fieldName, value);
                    } else {
                        result.put(fieldName, fit);
                    }
                }
            } catch (FileUploadException ex) {
                LOG.error("Parsing the request", ex);
            }

        }
        LOG.debug("getMapData.END");

        return result;
    }

    public static Object parseRequest(HttpServletRequest request, Class clazz) {
        return parseRequest(getMapData(request), clazz);
    }

    public static Object parseRequest(Map<String, Object> reqMap, Class clazz) 
    {
        if (reqMap != null && reqMap.size() > 0)
        {
            try
            {
                Object o = clazz.newInstance();
                Field[] fields = clazz.getDeclaredFields();
                for (Field f : fields) {
                    String methodName = "set" + Character.toUpperCase(f.getName().charAt(0)) + f.getName().substring(1);
                    
                    Class[] paramTypes = new Class[]{f.getType()};
                    Object[] arguments = null;
                    if (f.getType().getName().equals("String"))
                    {
                        arguments = new Object[]{reqMap.get(f.getName())};
                    }
                    else if (f.getType().getName().equals("int"))
                    {
                        arguments = new Object[]{Integer.valueOf(reqMap.get(f.getName()).toString())};
                    }
                    else if (f.getType().getName().equals("float") || f.getType().getName().equals("float") )
                    {
                        arguments = new Object[]{Double.valueOf(reqMap.get(f.getName()).toString())};
                    }
                    else 
                    {
                        arguments = new Object[]{reqMap.get(f.getName())};
                    }
                    
                    Method invokeMethod = clazz.getMethod(methodName, paramTypes);
                    invokeMethod.invoke(o, arguments);
                }
                Field[] parentFields = clazz.getSuperclass().getDeclaredFields();
                for (Field f : parentFields) {
                    String methodName = "set" + Character.toUpperCase(f.getName().charAt(0)) + f.getName().substring(1);
                    
                    LOG.debug("Type : " + f.getType());
                    
                    Class[] paramTypes = new Class[]{f.getType()};
                    Object[] arguments = new Object[]{reqMap.get(f.getName())};
                    
                    Method invokeMethod = clazz.getMethod(methodName, paramTypes);
                    invokeMethod.invoke(o, arguments);
                }
                return o;
            }
            catch (Exception ex)
            {
                LOG.error("Parsing the request", ex);
            }
        }
        return null;
    }
}
